/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package PuriON_Chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Iterator;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTextArea;

/**
 *
 * @author goajang
 */
public class PURION_Chat_Repeater implements Runnable{

    javax.swing.JTextArea textField;
    ServerSocket sSocket;
    Vector cSocketList;
    Thread sSocketListener;
    PURION_Chat clist;
    
    public PURION_Chat_Repeater(JTextArea tF)
    {
        textField = tF; // 외부로부터 받은 텍스트 에어리어
        clist = new PURION_Chat();
        
        System.out.println("repeat setup");
    }

    public void sendAll(String message)
    {
            System.out.println("모두에게 메세지를 보냅니다.");
            this.textField.setText(this.textField.getText() +"\n"+ message);
            
            PrintStream out;
            
            cSocketList = clist.getVector();
            
            for(int i=0;i<cSocketList.size();i++)
            {
                if (((Socket)cSocketList.get(i)).isConnected())
                {
                    
                    try {
                        out = new PrintStream(((Socket) cSocketList.get(i)).getOutputStream());
                        out.println(message);
                    } catch (IOException ex) {
                        Logger.getLogger(PURION_Chat_Repeater.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    
                }
                else
                {
                    cSocketList.elementAt(i);
                    i--;
                }
            }
    }
    
    public Vector getVector()
    {
        return clist.getVector();
    }
    
    public void run() {
        
        try {
            // 이 서버소켓은 사용자가 메세지를 서버에게 보낼때 여는 소켓을 받기 위한 서버소켓이다.
            sSocket = new ServerSocket(20008); //임의의 포트번호
            
            
            sSocketListener = new Thread(clist);
            sSocketListener.start();
            
        } catch (IOException ex) {
            Logger.getLogger(PURION_Chat.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        
        while(true)
        {
            try {

                System.out.println("repeater");
                
                Socket buffSoc = sSocket.accept();

                //BufferedInputStream buffInput= new BufferedInputStream(inn);
                //DataInputStream dataInput= new DataInputStream(buffInput);
                //r로 소켓에서 글을 받음.
                BufferedReader br = new BufferedReader( new InputStreamReader(buffSoc.getInputStream()));
   
                String r = br.readLine();
               
                
                //client에서 접속을 종료하여 QUIT메시지를 보내면 서버쪽 소켓백터에서 삭제해준다.
                if (r.equals("QUIT")){
                    for (Iterator i=cSocketList.iterator(); i.hasNext(); ){
                        Socket subsoc = (Socket) i.next();
                        if (subsoc.getInetAddress().getHostAddress().equals(buffSoc.getInetAddress().getHostAddress()))
                        {
                            cSocketList.remove(subsoc);
                            break;
                        }
                    }
                    
                }

                buffSoc.close();

                sendAll(r);
                

            } catch (IOException ex) {
                Logger.getLogger(PURION_Chat.class.getName()).log(Level.SEVERE, null, ex);
            }
        
        }
        
    }
    
}
